package com.tozed.android.launcher.simpleui;

import com.tozed.android.launcher.R;

import android.appwidget.AppWidgetHostView;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;

public class SimpleLauncherAppWidgetHostView extends AppWidgetHostView
{
	private static final String TAG = "SimpleLauncherAppWidgetHostView";
	private boolean mHasPerformedLongPress;
	private LayoutInflater mInflater;
	private CheckForLongPress mPendingCheckForLongPress;
	private SimpleUILauncher.State mState;

	public SimpleLauncherAppWidgetHostView(Context context)
	{
		super(context);
		mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}
	
	private void postCheckForLongClick()
	{
		mHasPerformedLongPress = false;
		
		if (mPendingCheckForLongPress == null)
			mPendingCheckForLongPress = new CheckForLongPress();
		
		mPendingCheckForLongPress.rememberWindowAttachCount();
		postDelayed(mPendingCheckForLongPress, ViewConfiguration.getLongPressTimeout());
	}
	
	@Override
	public void cancelLongPress()
	{
		super.cancelLongPress();
		
		mHasPerformedLongPress = false;
		if (mPendingCheckForLongPress != null)
			removeCallbacks(mPendingCheckForLongPress);
	}
	
	public int getDescendantFocusability()
	{
		super.getDescendantFocusability();
		return 393216;
	}

	// 错误视图
	protected View getErrorView(){
		return mInflater.inflate(R.layout.appwidget_error, this, false);
	}
	
	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev)
	{
		// TODO Auto-generated method stub
		// return super.onInterceptTouchEvent(ev);

		Log.i(TAG, "SimpleLauncherAppWidgetHostView " + mState);
		if (mState == SimpleUILauncher.State.EDIT)
			return true;
		
		if (mHasPerformedLongPress){
			mHasPerformedLongPress = false;
			return true;
		}
		
		switch (ev.getAction())
		{
		case MotionEvent.ACTION_MOVE:
		case MotionEvent.ACTION_DOWN:
			postCheckForLongClick();
			break;
			
		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_CANCEL:
			mHasPerformedLongPress = false;
			if (mPendingCheckForLongPress != null)
				removeCallbacks(mPendingCheckForLongPress);
			break;
		}
		
		return false;
	}
	
	public void setState(SimpleUILauncher.State state){
		mState = state;
	}
	
	class CheckForLongPress implements Runnable
	{
		private int mOriginalWindowAttachCount;

		CheckForLongPress(){
		}

		public void rememberWindowAttachCount(){
			mOriginalWindowAttachCount = getWindowAttachCount();
		}

		public void run()
		{
			if (mParent != null && hasWindowFocus() && mOriginalWindowAttachCount == getWindowAttachCount()
				  && mHasPerformedLongPress 
				  && performLongClick())
			{
				mHasPerformedLongPress = true;
			}
		}
	}
}
